//
//  ViewController.m
//  iOSPractice
//
//  Created by hoolai on 2018/11/17.
//  Copyright © 2018年 hoolai. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *labelName;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicatorLoad;
@property (weak, nonatomic) IBOutlet UIProgressView *progessLoading;
@property (weak, nonatomic) IBOutlet UITextField *textName;
@property (weak, nonatomic) IBOutlet UIButton *buttonStart;
@property (strong,nonatomic) AVAudioPlayer *audioPlayer;
@property (strong,nonatomic) NSTimer *timer;
- (IBAction)buttonStartTouched:(id)sender;
- (IBAction)nameTextChanged:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIStoryboard *sb=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    self.pictureViewController = [sb instantiateViewControllerWithIdentifier:@"vcPicture"];
    //NSLog(@"pic 2 %@",_pictureViewController);
    //[_activityIndicatorLoad setHidden:YES];
    [_activityIndicatorLoad setHidesWhenStopped:YES];
    
    [self musicLoad:AppSettings.loadingMusicURL];
    
}

//[开始]按钮被按下时执行的代码
- (IBAction)buttonStartTouched:(id)sender {
    //[_activityIndicatorLoad setHidden:NO];
    [_activityIndicatorLoad startAnimating];
    
    //[self.navigationController pushViewController:self.pictureViewController animated:YES];
    //[self presentViewController:self.pictureViewController animated:YES completion:nil];
    [self musicPlay];
    //静静地等待音乐播放完就会跳转界面。19秒左右
    //NSLog(@"%@",self.textName.text);
    self.textName.enabled=NO;
    //[self.audioPlayer stop];
    //[self createSkipButton];
    //Update v1.1: 延迟3秒后创建跳过按钮 (不用等啦!)
    [self performSelector:@selector(createSkipButton) withObject:nil afterDelay:3.0];
}

//Update v1.1: 尝试通过代码生成控件
- (void)createSkipButton{
    if([self.view viewWithTag:AppSettings.skipButtonTag]!=nil){
        NSLog(@"SkipButton is already exists");
        return; //存在该tag的子控件 说明skipButton已存在
    }
    UIButton *skipButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [skipButton setTag:AppSettings.skipButtonTag];
    //以开始按钮坐标为基准 往下平移作为跳过按钮的坐标
    skipButton.frame = self.buttonStart.frame;
    skipButton.transform = CGAffineTransformMakeTranslation(0, 100);
    skipButton.alpha = 0.0;
    //设置按钮文字属性
    //NSLog(@"color : %@",self.buttonStart.currentTitleColor);
    //NSLog(@"color2 : %@",[UIColor colorWithRed:0 green:0.478431 blue:1 alpha:1]);
    [skipButton setTitle:@"跳过" forState:UIControlStateNormal];
    [skipButton setTitleColor:AppSettings.myTextColor  forState:UIControlStateNormal];
    //将按钮添加到界面中
    [self.view addSubview:skipButton];
    //设置监听按钮点击事件
    [skipButton addTarget:self action:@selector(skipButtonTouched) forControlEvents:UIControlEventTouchUpInside];
    //设置按钮出现动画
    [UIView animateWithDuration:1.0 animations:^{
        skipButton.alpha = 1.0;
    }];
}

//Update v1.1: 添加按钮响应事件
- (void)skipButtonTouched{
    //跳过等待时间。
    //定时器检测到音乐停止就会自动作出界面跳转
    [self.audioPlayer stop];
}

//装载音频文件
- (void)musicLoad:(NSURL *)fileURL {
    NSError *err;
    self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&err];
    NSLog(@"%@",err);
    NSString *msg = [NSString stringWithFormat:@"音频文件声道数:%ld\n 音频文件持续时间:%g",self.audioPlayer.numberOfChannels,self.audioPlayer.duration];
    NSLog(@"%@",msg);
}

//播放音频
- (void)musicPlay {
    if([self.audioPlayer play]){
        [self.timer setFireDate:[NSDate distantPast]];
    }else{
        NSLog(@"音频错误");
    }
}

//设置计时器 用于检测音频播放状态
- (NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0 target:self
            selector:@selector(timerAction) userInfo:nil repeats:YES];
        [_timer setFireDate:[NSDate distantFuture]];//在创建计时器的时候把计时器先暂停。
    }return _timer;
}

//计时器的具体实现
- (void)timerAction{
    self.progessLoading.progress=self.audioPlayer.currentTime/self.audioPlayer.duration;
    //NSLog(@"%f : %f",self.audioPlayer.currentTime,self.audioPlayer.duration);
    
    if(self.audioPlayer.isPlaying==NO){//播放结束
        NSLog(@"播放完毕");
        
        //[self.navigationController pushViewController:self.pictureViewController animated:YES];
        //不知为何上面那一个跳转功能失效了
        NSLog(@"navigation %@",self.navigationController);
        //打印出来发现 navigationController 为 nil
        //界面传值：将当前text的值传入下一个界面的label中
        if(![self.textName.text isEqualToString:@""])
        [self.pictureViewController.labelWelcome setText:[NSString stringWithFormat:@"welcome\n%@",self.textName.text]];
        self.pictureViewController.labelWelcome.numberOfLines = 0;

        //使label大小自适应文字
        [self.pictureViewController.labelWelcome sizeToFit];
        //界面跳转
        [self presentViewController:self.pictureViewController animated:YES completion:nil];
        //设置label动画
        //下面一行代码会有无法执行动画的bug
        //[self.pictureViewController welcomeAnimation];
        //下面一行代码可以正确执行动画，但感觉不是最优解
        //我将动画执行的方法放到了PictureViewController类中
        //[self.pictureViewController performSelector:@selector(welcomeAnimation) withObject:nil afterDelay:2.0];
        
        [self.activityIndicatorLoad stopAnimating];
        //暂停计时器
        //[self.timer setFireDate:[NSDate distantFuture]];
        //停止并销毁计时器
        [self.timer invalidate];
        self.timer=nil;//timer是strong指针，直接赋值nil即可释放。
    }
}

- (IBAction)nameTextChanged:(id)sender {
    
}
@end
